<template>
  <base-breadcrumb :title="$route.meta.title">
    <!-- 职工代表大会编辑 -->

    <a-spin :spinning="loading">
      <!-- 表格 -->
      <a-card :bordered="false">
        <a-form-model ref="ruleForm" :model="form" :label-col="{ span: 6 }" :wrapper-col="{ span: 18 }" :rules="editModel != 0 ? rules : {}">
          <title-name title="基础信息"></title-name>
          <custom-form :isEmit="false" :formList="formList" :form="form" :editModel="editModel == 0 ? '' : ''"
                       @selectOrg="selectOrg"
                       @getProjectInfo="getProjectInfo"> </custom-form>
        </a-form-model>
      </a-card>
      <a-card :bordered="false">
        <title-name title="图纸清单关联"></title-name>
        <div v-if="editModel != 0">
          图纸清单关联：
          <a-button class="mb12" icon="plus" @click="openModal()" :disabled="!form.projectId"></a-button>
        </div>
        <s-table
          :scroll="{ y: 500 }"
          ref="table"
          size="default"
          rowKey="drawId"
          :columns="editModel != '0' ? columns : columnsLook"
          :data="loadData"
          :alert="true"
          show-size-changer
          show-quick-jumper
          :showPagination="false"
        >
          <span slot="operation" slot-scope="text, record, index">
            <span>
              <a-popconfirm title="确定要删除?" @confirm="() => handleRemove(index)">
                <a>删除</a>
              </a-popconfirm>
            </span>
          </span>
        </s-table>
      </a-card>
      <a-card :bordered="false" v-if="comment && form.status == 'PAST'">
        <title-name title="评论"></title-name>
        <a-tabs :activeKey="currentKey" @change="changeKey">
          <a-tab-pane key="1" tab="全部评论" style="max-height: 600px; overflow-y: scroll">
            <template v-if="!form.commentDTO">
              <div class="comments" v-for="item of form.commentDTOS" :key="item.id">
                <span class="action" v-btnPermission="'tm_019_rco_07'">
                  <a
                    @click="
                      item.isEdit = true
                      comments = {}
                    "
                    >回复</a
                  >
                  <template v-if="(item.children == null || item.children.length === 0)&&item.commentatorId === currentUserId">
                    <a-divider type="vertical" />
                    <a @click="del(item.id)">删除</a>
                  </template>
                </span>
                <!-- 评论 -->
                <span style="font-weight: bold; font-size: 16px">{{ item.commentator }}</span
                ><span style="margin-left: 10px">评论时间：{{ item.createTime }}</span>
                <p>{{ item.commentOption }}</p>
                <upload-list v-if="item.fileInfoVOS" upload-type="image" :business-code="'OF11'" :edit-model="editModel" count="3" :del-request="false" :upload-arrys.sync="item.fileInfoVOS" multiple />
                <!-- 回复 -->
                <div v-if="item.children != null">
                  <div v-for="i of item.children" :key="i.id">
                    <p>回复： {{ i.commentOption }}</p>
                    <upload-list v-if="i.fileInfoVOS" upload-type="image" :business-code="'OF11'" :edit-model="editModel" count="3" :upload-arrys.sync="i.fileInfoVOS" multiple />
                  </div>
                </div>
                <!-- 回复填写 -->
                <div v-if="item.isEdit" style="margin-left: -20px">
                  <a-divider />
                  <a-form-model ref="commentsFrom" :model="comments" :label-col="{ span: 6 }" :wrapper-col="{ span: 18 }" :rules="rulesComments">
                    <a-row :gutter="24">
                      <a-col span="24">
                        <a-form-model-item label="回复" prop="commentOption">
                          <BaseTextarea v-model="comments.commentOption" />
                        </a-form-model-item>
                      </a-col>
                      <a-col span="24"> <upload-list style="margin-left: 70px" upload-type="image" :business-code="'OF11'" :edit-model="2" count="3" :upload-arrys.sync="comments.fileInfoVOS" multiple /></a-col> </a-row
                  ></a-form-model>
                  <div class="btn_box">
                    <a-button class="button_right" type="primary" @click="item.isEdit = false">关闭</a-button>
                    <a-button type="primary" @click="addComment(comments, item)">确定</a-button>
                  </div>
                </div>

                <a-divider style="margin-bottom: 5px" />
              </div>
            </template>
            <template v-else>
              <empty />
            </template>
          </a-tab-pane>
          <a-tab-pane key="2" tab="我要评论" style="max-height: 400px">
            <div class="addcomments">
              <a-form-model ref="commentsFrom" :model="comments" :label-col="{ span: 6 }" :wrapper-col="{ span: 18 }" :rules="rulesComments">
                <a-row :gutter="24">
                  <a-col span="24">
                    <a-form-model-item label="评论" prop="commentOption">
                      <BaseTextarea v-model="comments.commentOption" />
                    </a-form-model-item>
                  </a-col>

                  <a-col span="24">
                    <a-form-model-item label="图片上传">
                      <upload-list upload-type="image" :business-code="'OF11'" :edit-model="2" count="3" :upload-arrys.sync="comments.fileInfoVOS" multiple /> </a-form-model-item></a-col></a-row
              ></a-form-model>
              <div class="btn_box">
                <a-button class="button_right" type="primary" @click="currentKey = '1'">取消</a-button>
                <a-button type="primary" @click="addComment(comments)">确定</a-button>
              </div>
            </div></a-tab-pane
          >
        </a-tabs>
      </a-card>

      <!-- 页脚操作栏 -->
      <div class="btn_box page-btn-right-top" v-if="editModel != 0">
        <a-button class="button_right" v-if="form.status == 'REJECTED'" type="primary" :loading="loadingBtn.REJECTED" @click="handleSubmit('REJECTED')">保存</a-button>
        <a-button v-else class="button_right" type="primary" :loading="loadingBtn.DRAFT" @click="handleSubmit('DRAFT')">保存草稿</a-button>
        <a-button class="button_right" type="primary" :loading="loadingBtn.SUBMITTED" @click="handleSubmit('SUBMITTED')">提交</a-button>
        <a-button @click="handleActiveClose">关闭</a-button>
      </div>

      <div v-else class="btn_box page-btn-right-top">
        <a-button @click="handleActiveClose">关闭</a-button>
      </div>
    </a-spin>
    <!-- 表单弹窗 -->
    <drawing-modal ref="drawingModal" :form="form" :visible.sync="visible" @confirm="confirm"
                   v-if="visible"
                   isQuery
                   :selectKey="selectKey"
                   :status="0"
                   :searchArr="searchArr" />
    <selectApprover :businessId="businessId"  :processConfig="setProcessConfig" ></selectApprover>
  </base-breadcrumb>
</template>

<script>
import { getDrawDesign, addDrawDesign, updateDrawDesign, addComment, delComment, getDrawDesignList, getIsVersion } from '@/api/technical/designFM'
import BaseEditPage from '@/views/baseEditPage' // 编辑详情页基础配置
import SelectSubCompany from '@/components/Select/SelectSubCompany' // 分公司
import SelectProject from '@/components/Select/SelectProject' // 分公司
import UploadList from '@/components/UploadList'
import Selector from '@/components/Select/Selector'
import SelectPersonByProject from '@/components/Select/SelectPersonByProject' // 人员选择
import drawingModal from './drawingModal.vue' // 表单弹窗
import { Empty } from 'ant-design-vue'
import { majorTypeSelectListTree, queryProjectListByTree } from '@/api/technology'
const searchArr = [
  // {
  //   name: '专业类别',
  //   value: 'projectLocation2',
  //   type: Selector
  // },
  {
    name: '工程部位',
    type: 'tree-select',
    value: 'projectListId',
    attrs: {
      replaceFields: {children:'childList', title:'name', key:'id', value: 'id' },
      showSearch: true,
      treeNodeFilterProp: 'title'
    },
    data: []
  },
  {
    name: '图纸名称',
    value: 'name',
    type: 'input'
  },
  {
    name: '图号',
    value: 'drawNum',
    type: 'input'
  }
]
const columns = [
  {
    title: '工程部位',
    dataIndex: 'projectLocation'
  },
  {
    title: '专业类别',
    dataIndex: 'majorTypeName'
  },
  {
    title: '图纸名称',
    dataIndex: 'name'
  },
  {
    title: '图号',
    dataIndex: 'drawNum'
  },

  {
    title: '操作',
    dataIndex: 'operation',
    width: '230px',
    scopedSlots: { customRender: 'operation' }
  }
]
const columnsLook = [
  {
    title: '序号',
    width: 80,
    dataIndex: 'index',
    customRender() {
      return arguments[2] + 1
    }
  },
  {
    title: '工程部位',
    dataIndex: 'projectLocation'
  },
  {
    title: '专业类别',
    dataIndex: 'majorTypeName'
  },
  {
    title: '图纸名称',
    dataIndex: 'name'
  },
  {
    title: '图号',
    dataIndex: 'drawNum'
  },

  {
    title: '出图时间',
    dataIndex: 'plotDate'
  }
]
export default {
  name: 'a' + Date.now(),
  extends: new BaseEditPage(),
  components: {
    drawingModal,
    SelectPersonByProject,
    UploadList,
    Empty
  },
  data() {
    this.columns = columns
    this.columnsLook = columnsLook

    return {
      projectDeptId: '',
      selectKey: [],
      searchArr: searchArr,
      loading: false, // 加载控件
      visible: false, //弹窗控件
      editModel: 0, // 操作状态:0 查看;1 编辑;2 新增
      form: { detailDTOS: [], projectDeptId: void 0,  curId: '', projectId: "", branchComId: "", receiverId: '' }, // 表单
      comments: {},
      comment: false,
      id: '',
      loadingBtn: {
        DELETE: false,
        DRAFT: false,
        SUBMITTED: false,
        REJECTED: false
      },
      currentKey: '1',
      copyForm: {},
      dialogForm: {},
      rules: {
        majorTypeId: [{ required: true, message: '请选择' }],
        drawTypeId: [{ required: true, message: '请选择' }],
        deepDrawTypeId: [{ required: true, message: '请选择' }],
        name: [{ required: true, message: '请输入' }],
        num: [{ required: true, message: '请输入' }],
        drawVersion: [{ required: true, message: '请输入' }],
        receiptDate: [{ required: true, message: '请选择' }],
        sendDepartment: [{ required: true, message: '请输入' }],
        numCopies: [{ required: true, message: '请输入' }],
        receiverId: [{ required: true, message: '请输入' }],
        options: [{ required: true, message: '请输入' }]
      },
      rulesComments: {
        commentOption: [{ required: true, message: '请输入' }]
      },
      loadData: () => {
        return new Promise((resolve, reject) => {
          resolve({
            data: this.form.detailDTOS || []
          })
        })
      },
      currentUserId: '',
      init: false, // 初始化控件
      titles: ['设计图纸管理查看', '设计图纸管理编辑', '设计图纸管理新增'],
      //获取流程配置值
      processConfig: null,
      //点击提交发送流程配置值
      setProcessConfig: null,
      businessId: null,
      list: []
    }
  },

 async mounted() {
    this.$route.meta.title = ['设计图纸管理查看', '设计图纸管理编辑', '设计图纸管理新增'][this.editModel]
   this.currentUserId = this.$userInfo().id
    // 不为添加时请求详情
    if (this.editModel != 2) {
      this.getDetails()
    } else {
      this.form.curId = this.$route.query.projectId
      this.form.branchComId = this.$route.query.branchComId
      this.majorTypeSelectListTree()
      this.queryProjectListByTree()
      this.$nextTick(() => {
        this.init = true
      })
    }
    //获取通过获取流程配置值
    this.processConfig = await this.$getConfigFn('technical_draw_design')

  },
  props: {
    isAudit: {
      // 是否作为审批详情
      type: Boolean,
      default: false
    }
  },
  watch: {
    isAudit: {
      immediate: true,
      handler(val) {
        if (val) {
          this.$nextTick(() => {
            this.editModel = 0
          })
        }
      }
    }
  },
  computed: {
    formList() {
      let that = this;
      return [
        {
          label: '所属单位',
          type: 'orgTree',
          keyName: 'curId',
          rules: [{ required: true, message: '请选择项目名称', trigger: 'change' }],
          span: 16,
          isAutoSelectFirst:true,
          isNeedAuth:true,
          checkStrictly: true,
          disabled:true,
          statusSet:[1,2,3,4,5,6],
          isQueryProjecDetail: true
        },
        {
          keyName: 'majorTypeId',
          label: '专业类别',
          type: 'ATreeSelect',
          disabled: that.editModel == 0,
          attrs: {
            replaceFields: {children:'children', title:'majorName', key:'id', value: 'id' },
            showSearch: true
          },
          data: that.list,
          change() {
            that.form.detailDTOS = []
            that.$refs.table.refresh(true)
          }
        },
        {
          keyName: 'drawTypeId',
          label: '图纸类型',
          type: Selector,
          disabled: that.editModel == 0,
          attrs: {
            selectType: '10',
            urlType: 'technical'
          },
          change() {
            that.form.detailDTOS = []
            that.$refs.table.refresh(true)
          }
        },
        {
          keyName: 'deepDrawTypeId',
          label: '深化图纸类型',
          hidden: that.form.drawTypeId != '759320991137665024',
          type: Selector,
          disabled: that.editModel == 0,
          attrs: {
            selectType: '11',
            urlType: 'technical'
          }
        },
        {
          type: 'BaseInput',
          label: '文件名称',
          disabled: that.editModel == 0,
          keyName: 'name'
        },
        {
          type: 'BaseInput',
          label: '文件编号',
          disabled: that.editModel == 0,
          keyName: 'num'
        },
        {
          keyName: 'receiptDate',
          type: 'a-date-picker',
          label: '收文日期',
          disabled: that.editModel == 0,
          attrs: {
            valueFormat: 'YYYY-MM-DD'
          }
        },
        {
          type: 'BaseInput',
          label: '版本号',
          disabled: that.editModel == 0,
          keyName: 'drawVersion'
        },

        {
          type: 'BaseInput',
          label: '发文部门',
          disabled: that.editModel == 0,
          keyName: 'sendDepartment'
        },
        {
          type: 'BaseInputNumber',
          label: '份数',
          disabled: that.editModel == 0,
          attrs: {
            min: 0
          },
          keyName: 'numCopies'
        },
        {
          keyName: 'receiverId',
          type: SelectPersonByProject,
          label: '接收人',
          disabled: that.editModel == 0,
          wrap: true,
          attrs: {
            // [currentLabel.sync]: form.returnApplier,
            isOrg: true,
            showSearch: true,
            orgId: that.projectDeptId
            // mode: 'combobox',
            // optionLabelProp: 'children'
          },
          personChanged: (e) => {
            that.form.receiverName = e?.employeeName
          }
        },
        {
          type: 'BaseTextarea',
          label: '内容摘要',
          disabled: that.editModel == 0,
          span: 24,
          keyName: 'options'
        },
        {
          keyName: 'fileInfos',
          type: 'uploadFile',
          disabled: that.editModel == 0,
          label: '附件',
          span: 24,
          businessCode: 'BIM03'
        }
      ]
    }
  },
  methods: {
    queryProjectListByTree() {
      const data = {
        branchComId: this.form.branchComId,
        projectId: this.form.curId
      }
      queryProjectListByTree(data).then((res) => {
        this.generalData(res.data)
        this.searchArr[0].data = res.data
      }).catch(() => {
        this.loading2 = false
      })
    },

    generalData(data) {
      data.forEach(item=>{
        if(item.childList&&item.childList.length) {
          item.disabled = true
          this.generalData(item.childList)
        }
      })
    },

    majorTypeSelectListTree() {
      majorTypeSelectListTree( this.form.curId).then(res=>{
        res.data.forEach(item=>{
          item.majorName = item.programmeName
          item.disabled = true
        })
        this.list = res.data
      })
    },
    selectOrg(val) {
      if(val.length&&val.length < 2) {
        this.form.branchComId = val[val.length - 1].orgId
      } else if(val.length >= 2 ) {
        this.form.branchComId = val[val.length - 2].orgId
        this.form.projectId = val[val.length - 1].projectId
      }
    },
    getProjectInfo(info) {
      this.projectDeptId = info.projectDeptOrgId
      this.$set(this.form, 'projectDeptId', info.projectDeptOrgId)
    },
    openModal() {
      if (!this.form.majorTypeId) {
        this.$message.warning('请先选择专业类别')
        return
      }
      if (!this.form.drawTypeId) {
        this.$message.warning('请先选择图纸类型')
        return
      }
      this.visible = true
    },
    changeKey(key) {
      this.currentKey = key
      this.comments = {}
    },
    del(id) {
      this.$delList3(
        delComment,
        (res) => {
          this.getDetails()
        },
        { id: id },
        null
      )
    },
    addComment(comments, item = {}) {
      if (comments.commentOption) {
        comments.drawId = this.id
        comments.parentId = item.id || void 0
        this.loading = true
        addComment(comments)
          .then((res) => {
            console.log()
            if (!comments.parentId) {
              this.changeKey('1')
            }
            this.$message.success(item.id ? '回复成功' : '评论成功')
            this.getDetails()
          })
          .catch(() => {
            this.loading = false
            this.$message.warning(err.data.message)
          })
      } else {
        console.log(item)
        this.$message.warning(item.id ? '请输入回复内容' : '请输入评论内容')
      }
    },
    getDetails() {
      this.loading = true
      console.log(this.id)
      getDrawDesign({ id: this.id })
        .then((res) => {
          this.loading = false
          res.data.commentDTOS?.forEach((i) => {
            i.isEdit = false
          })
          this.form = res.data
          if(this.form.projectId) {
            this.form.curId =  this.form.projectId
            this.majorTypeSelectListTree()
            this.queryProjectListByTree()
          } else {
            this.form.curId =  this.form.branchComId
          }
          this.form.detailDTOS = this.form.detailDTOS || []

          this.$refs.table.loadData()
          this.$nextTick(() => {
            this.init = true
          })
        })
        .catch(() => {
          this.loading = false
        })
    },
    confirm() {
      this.$refs.table.refresh(true)
    },
    handleOpen(e) {
      this.visible = true
    },
    handleRemove(index) {
      this.form.detailDTOS.splice(index, 1)
      this.$refs.table.refresh(true)
    },
    validateForm() {
      let flag = false
      this.$refs.ruleForm.validate((e) => {
        if (e) {
          flag = true
        }else {
          this.$message.warning('请填写完所有必填项信息')
        }
      })
     if(!this.form.fileInfos || this.form.fileInfos.length===0) {
       flag = false
       this.$message.warning('请上传附件')
     }
      return flag
    },
    isVersion() {
      getIsVersion({ id: this.form.projectId, name: this.form.drawVersion }).then((res) => {})
    },
    /**
     * 提交表单
     */
    async handleSubmit(status) {
      this.setProcessConfig = null;
      if (status == 'SUBMITTED' && !this.validateForm()) {
        return
      }
      if (status == 'SUBMITTED' && this.form.detailDTOS?.length === 0) {
        this.$message.warning('请选择设计图纸!')
        return
      }
      let projectListName = []
      if(this.form.detailDTOS?.length) {
        this.form.detailDTOS.forEach(item=>{
          projectListName.push(item.projectLocation)
        })
      }
      this.loading = true
      this.loadingBtn[status] = true
      if (status == 'SUBMITTED') {
        let res = await getDrawDesignList({
        needCount: false,
        query: {
          projectId: this.form.projectId,
          name: this.form.name,
          professionalTypeId: this.form.professionalTypeId,
          drawTypeId: this.form.drawTypeId,
          deepDrawTypeId: this.form.deepDrawTypeId,
          num: this.form.num,
          receiptBeginDate: this.form.receiptDate,
          receiptEndDate: this.form.receiptDate,
          drawVersion: this.form.drawVersion
        }
      })

      if (res.data.length > 0 && res.data[0].status != 'DRAFT' && res.data[0].status != 'REJECTED') {
        this.$message.warning('版本号不可重复')
        this.loading = false
        this.loadingBtn[status] = false
        return
      }
      }
      let form = this.$clone(this.form)
      form.status = status
      form.projectListName = projectListName.join(",")
      let api = [updateDrawDesign, addDrawDesign][this.editModel - 1]
      // 根据操作切换url地址
      this.submitApprovalConfirm(status == 'SUBMITTED' ? this.processConfig : 6, (flag)=>{
        if(!flag) {
          this.loading = false
          this.loadingBtn[status] = false
          return
        }
      api(form)
        .then((res) => {
          this.loading = false
          this.loadingBtn[status] = false
          this.$message.success(status == 'SUBMITTED' ? '提交成功！' : '保存成功')
          if(status =='SUBMITTED') {
            //提交时，返回id
              this.businessId = res.data.id;
              this.setProcessConfig = this.processConfig;
              return
            }else{
            this.$multiTab.close()
          }

        })
        .catch(() => {
          this.loadingBtn[status] = false
          this.loading = false
          this.$message.warning(err.data.message)
        })
      })
    }
  }
}
</script>

<style lang="less" scoped>
.comments {
  padding: 0 10px 10px 10px;
  position: relative;

  p {
    margin-top: 5px;
  }
  .action {
    position: absolute;
    right: 20px;
    top: 0;
  }
  /deep/ .ant-form-item {
    .ant-form-item-label {
      height: 28px;
      width: 70px;
      line-height: 22px;
      padding: 6px 4px 0 0;
      text-align: right;
      white-space: pre-wrap;
      overflow: visible;
    }
    .ant-form-item-control-wrapper {
      width: calc(100% - 70px);
    }
  }
}
.addcomments {
  /deep/ .ant-form-item {
    .ant-form-item-label {
      height: 28px;
      width: 80px;
      line-height: 22px;
      padding: 6px 4px 0 0;
      text-align: right;
      white-space: pre-wrap;
      overflow: visible;
    }
    .ant-form-item-control-wrapper {
      width: calc(100% - 80px);
    }
  }
}
</style>
